import {extend, LocalStorage} from 'quasar';
import {defaultValue} from 'src/lib/util/box'
import Vue from 'vue';

const save = (state) => {
  LocalStorage.set('box', state.box);
}

export const add = (state, payload) => {
  for (const i of state.box) {
    if (i.id === payload.id) return;
  }
  state.box.push({
    ...defaultValue(),
    id: payload.id,
    star: payload.star
  });
  save(state);
}

export function update (state, payload) {
  for (let i in state.box) {
    if (state.box[i].id === payload.id) {
      const data = {
        ...defaultValue(),
        ...state.box[i],
        ...payload
      }
      deepSet(state.box[i], data);
      save(state);
    }
  }
}

export const remove = (state, payload) => {
  for (const i in state.box) {
    if (state.box[i].id === payload) state.box.splice(Number.parseInt(i), 1);
  }
  save(state);
}

export const updateName = (state, payload) => {
  state.name = payload;
  LocalStorage.set('name', state.name);
}

export const importState = (state, payload) => {
  deepSet(state, payload);
  save(state);
}

export const forceImportState = (state, payload) => {
  state = extend(true, payload, {});
  save(state);
}

function deepSet(object, newObject) {
  for(const i in newObject) {
    if (typeof newObject[i] === 'object') deepSet(object[i], newObject[i]);
    else if (object[i]) object[i] = newObject[i];
    else Vue.set(object, i, newObject[i]);
  }
}
